package com.aididi.designpatter;


import java.util.Hashtable;

/**
 * @Auther: xuzexiang
 * @Date: 2018-10-29 0029 11:11
 * @Description:    原型模式
 *          原型模式就是将一个对象作为原型，使用clone()方法来创建新的实例
 *          原型模式指在创建重复对象的同时保持性能。 这种类型的设计模式属于创建模式，因为此模式提供了创建对象的最佳方法之一。
 */
//创建一个实现Clonable接口的抽象类
public abstract  class PrototypeDemo implements Cloneable{

    public static void main(String[] args) {
        ShapeCache.loadCache();
        Shape2 clonedShape1 = ShapeCache.getShape("1");
        System.out.println("Shape : " + clonedShape1.getType());

        Shape2 clonedShape2 = ShapeCache.getShape("2");
        System.out.println("Shape : " + clonedShape2.getType());

        Shape2 clonedShape3 = ShapeCache.getShape("3");
        System.out.println("Shape : " + clonedShape3.getType());

    }
}

abstract class Shape2 implements Cloneable{
    private String id;
    protected String type;

    abstract void draw();

    public String getType(){
        return type;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public Object clone() {
        Object clone = null;

        try {
            clone = super.clone();

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return clone;
    }
}

//创建扩展上述类的具体类
class Rectangle2 extends Shape2 {

    public Rectangle2(){
        type = "Rectangle";
    }

    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}

 class Square2 extends Shape2 {

    public Square2(){
        type = "Square";
    }

    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

class Circle2 extends Shape2 {

    public Circle2(){
        type = "Circle";
    }

    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

//创建一个类来获取具体的类，并将它们存储在Hashtable中。
class ShapeCache {

    private static Hashtable<String, Shape2> shapeMap  = new Hashtable<String, Shape2>();

    public static Shape2 getShape(String shapeId) {
        Shape2 cachedShape = shapeMap.get(shapeId);
        return (Shape2) cachedShape.clone();
    }

    // for each shape run database query and create shape
    // shapeMap.put(shapeKey, shape);
    // for example, we are adding three shapes

    public static void loadCache() {
        Circle2 circle = new Circle2();
        circle.setId("1");
        shapeMap.put(circle.getId(),circle);

        Square2 square = new Square2();
        square.setId("2");
        shapeMap.put(square.getId(),square);

        Rectangle2 rectangle = new Rectangle2();
        rectangle.setId("3");
        shapeMap.put(rectangle.getId(), rectangle);
    }
}





